﻿/*
 * Copyright (c) Martin Kinkelin
 *
 * See the "License.txt" file in the root directory for infos
 * about permitted and prohibited uses of this code.
 */

using System;
using System.Windows.Forms;

namespace Jarf
{
	/// <summary>
	/// Base of all dialogs.
	/// Sets some typical properties for dialogs, contains an "OK" and a "Cancel"
	/// button and manages the DialogResult in a way that
	/// a) DialogResult.Yes means that the changes have been applied,
	/// b) DialogResult.No means that either there were no changes or the changes
	///    have been discarded.
	/// </summary>
	public partial class BaseDialog : BaseForm
	{
		/// <summary>
		/// Gets or sets a value indicating whether the dialog has changed.
		/// If it has changed and the dialog is being closed without pressing
		/// the OK button, the user will be prompted to apply or discard the changes.
		/// </summary>
		protected bool HasChanged { get; set; }



		public BaseDialog()
		{
			InitializeComponent();
		}


		private void BaseDialog_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (HasChanged && DialogResult != DialogResult.OK)
			{
				DialogResult answer = MessageBox.Show("Would you like to save your changes?",
					"Pending changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

				if (answer == DialogResult.Cancel)
				{
					e.Cancel = true;
					return;
				}

				// simulate having pressed one of the buttons
				DialogResult = (answer == DialogResult.Yes ? DialogResult.OK : DialogResult.Cancel);
			}

			if (HasChanged && DialogResult == DialogResult.OK)
			{
				if (!ApplyChanges())
				{
					e.Cancel = true;
					return;
				}

				DialogResult = DialogResult.Yes;
			}
			else
				DialogResult = DialogResult.No;
		}


		/// <summary>
		/// Tries to apply the changes.
		/// If the method returns false, the dialog is not closed.
		/// </summary>
		protected virtual bool ApplyChanges()
		{
			throw new NotImplementedException("BaseDialog.ApplyChanges()");
		}
	}
}
